<?php

namespace app\admin\controller;

use think\Controller;
use app\admin\model\Admin as AdminModel;
use app\admin\validate\Admin as AdminValidate;

class Admin extends Controller
{
    protected $AdminModel;
    protected $AdminValidate;

    public function __construct()
    {
        if (!session('adminId')) {
            $this->redirect('login/index');
        }
        $this->AdminModel = new AdminModel();
        $this->AdminValidate = new AdminValidate();
        $this->gid = session('adminGid');
    }

    public function index()
    {
        $query = [
            'ispage' => true,
            'where' => [
                'gid' => $this->gid,
            ],
        ];
        $adminRes = $this->AdminModel->getLst($query);

        return view('index', [
            'admin' => $adminRes,
        ]);
    }

    public function add()
    {
        if (request()->isPost()) {
            $data = input();
            $data['gid'] = $this->gid;
            if (!$this->AdminValidate->scene('add')->check($data)) {
                $this->error($this->AdminValidate->getError());
            }
            $res = $this->AdminModel->save($data);
            if ($res) {
                $this->success('新增成功', 'admin/index');
            } else {
                $this->error('新增失败,请检查重试');
            }
        }

        return view('add');
    }

    public function edit($id)
    {
        $adminRes = $this->AdminModel->get($id);
        if (request()->isPost()) {
            $data = input();
            $data['gid'] = $this->gid;
            $isCheck = $this->AdminModel->CheckData($data, 0);
            if (!$isCheck) {
                $this->error('原始密码错误');
            }
            if (!$this->AdminValidate->scene('edit')->check($data)) {
                $this->error($this->AdminValidate->getError());
            }
            $data['password'] = $data['newpassword'];
            unset($data['newpassword']);
            unset($data['repassword']);
            $res = $adminRes->save($data);
            if ($res) {
                $this->success('编辑成功', 'admin/index');
            } else {
                $this->error('编辑失败,请检查重试');
            }
        }

        return view('edit', [
            'admin' => $adminRes,
        ]);
    }

    public function del($id)
    {
        if (request()->isPost()) {
            $res = $this->AdminModel->destroy($id);
            if ($res) {
                return 1;
            } else {
                return 0;
            }
        }
    }
}
